package com.texas_android.app.View;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.texas_android.app.Appconfig.AppConfig;
import com.texas_android.app.Appconfig.AppContext;
import com.texas_android.app.Appconfig.MyApplication;
import com.texas_android.app.R;
import com.texas_android.app.http.Api;
import com.texas_android.app.http.ResponseHandler;
import com.texas_android.app.http.bean.SearchResultBean;
import com.texas_android.app.http.bean.Version;
import com.texas_android.app.http.bean.company.CompanyBean;
import com.texas_android.app.http.bean.perssion.PerssionBean;
import com.texas_android.app.http.bean.perssion.PerssionListResultBean;
import com.texas_android.app.utils.AppOperator;
import com.texas_android.app.utils.DialogHelper;
import com.texas_android.app.utils.JsonParser;
import com.texas_android.app.utils.Logger;
import com.texas_android.app.utils.dateBase.DataBaseHelper;
import com.texas_android.app.utils.downLoan.CheckUpdateManager;
import com.texas_android.app.utils.downLoan.DownloadService;
import com.universal_library.permission.Acp;
import com.universal_library.permission.AcpListener;
import com.universal_library.permission.AcpOptions;
import com.universal_library.weight.AppToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

/**
 * 搜索页面
 */
public class SearchActivity extends Activity implements View.OnClickListener, CheckUpdateManager.RequestPermissions {
    @Bind(R.id.bt_search)
    LinearLayout bt_search;

    @Bind(R.id.et_search)
    EditText et_search;
    @Bind(R.id.iv_speak)
    ImageView iv_speak;

    @Bind(R.id.ll_loginout)
    LinearLayout ll_loginout;

    private boolean isSpaking = false;
    //听写对象
    private SpeechRecognizer mIat;
    AnimationDrawable animationDrawable;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
    private DataBaseHelper dataBaseHelper;

    private DialogHelper.ZXQbListDialog dialog;

    private boolean isHaveInternet = true;//是否可以连接到服务器

    private ResponseHandler searchHandler = new ResponseHandler(this, false, "查询") {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, final String responseString) {
            super.onSuccess(statusCode, headers, responseString);
            if (baseBean.getStatus().equals("0")) {
                if (baseBean.getType() == 1) {
                    SearchResultBean resultBean = AppOperator.createGson().fromJson(responseString, new TypeToken<SearchResultBean>() {
                    }.getType());
                    CompanyBean companyBean = resultBean.getCompanyBean().get(0);
                    //查询结果部门
                    Intent intent = new Intent(SearchActivity.this, CompanyInfoActivity.class);
                    intent.putExtra("companyBean", companyBean);
                    overridePendingTransition(R.anim.slide_in_top, R.anim.slide_in_top);
                    startActivity(intent);
                } else {
                    final PerssionListResultBean perssionListResultBeanr = AppOperator.createGson().fromJson(responseString, new TypeToken<PerssionListResultBean>() {
                    }.getType());
                    showPersion(perssionListResultBeanr.getPerssionBean());
                }
            } else {
                AppToast.showToast(SearchActivity.this, "", baseBean.getStatusDesc());
            }
        }
    };

    private void showPersion(List<PerssionBean> listPersionre) {
        List<String> mdata = new ArrayList<>();
        final List<PerssionBean> listPersion = listPersionre;
        if (listPersionre.size() > 1) {
            for (PerssionBean bean : listPersion) {
                String showInfo = "<font color='#404040'> 姓名：</font>" + bean.getName()
                        + "<font color='#404040'>  年龄：</font>" + bean.getAge()
                        + "<font color='#404040'>  部门：</font>" + bean.getDeptFullName();
                mdata.add(showInfo);
            }
            if (dialog != null && dialog.isShowing()) {
                return;
            }
            dialog = DialogHelper.openZxListDialog(SearchActivity.this, mdata, "请确认您要查询的信息", 06, new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    dialog.dismiss();
                    PerssionBean perssionBean = listPersion.get(i);
                    //结果查询的人
                    Intent intent = new Intent(SearchActivity.this, PerssonInfoActivity.class);
                    intent.putExtra("perBean", perssionBean);
                    overridePendingTransition(R.anim.slide_in_top, R.anim.slide_in_top);
                    startActivity(intent);
                }
            }, new DialogHelper.OnItemSelectListenter() {
                @Override
                public void mySelect(int dex) {
                    if (dex <= 6 && dex < listPersion.size()) {
                        try {
                            dialog.dismiss();
                            PerssionBean perssionBean = listPersion.get(dex);
                            //结果查询的人
                            Intent intent = new Intent(SearchActivity.this, PerssonInfoActivity.class);
                            intent.putExtra("perBean", perssionBean);
                            AppContext.setBean(perssionBean);
                            overridePendingTransition(R.anim.slide_in_top, R.anim.slide_in_top);
                            startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                            AppToast.showToast(SearchActivity.this, "您说的我不明白", "请手动选择");
                        }

                    } else {
                        AppToast.showToast(SearchActivity.this, "您说的我不明白", "请手动选择");
                    }

                }
            });
//                        Intent intent=new Intent(SearchActivity.this,DialogActivity.class);
//                        startActivity(intent);
        } else {
            if (listPersion != null && listPersion.size() > 0) {
                Intent intent = new Intent(SearchActivity.this, PerssonInfoActivity.class);
                intent.putExtra("perBean", listPersion.get(0));
                AppContext.setBean(listPersion.get(0));
                AppContext.setBean(listPersion.get(0));
                overridePendingTransition(R.anim.slide_in_top, R.anim.slide_in_top);
                startActivity(intent);
            } else {
                searchCompany();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        initView();
        CheckUpdateManager manager = new CheckUpdateManager(this, true);
        manager.setCaller(this);
        manager.checkUpdate();
    }


    protected void initView() {
        AppContext.addActivity(this);
//        iv_speak.setOnTouchListener(this);
        animationDrawable = (AnimationDrawable) iv_speak.getDrawable();
        animationDrawable.selectDrawable(8);
        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(SearchActivity.this, mInitListener);
        try {
            isHaveInternet = AppContext.ping(1, "192.168.1.2");
        } catch (Exception e) {
            e.printStackTrace();
        }
//        Cursor cursor = db.query()
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            Log.d("TAG", "初始化失败SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                AppToast.showToast(SearchActivity.this, "", "语音模块初始化失败");
            }
        }
    };

    @OnClick({R.id.bt_search, R.id.iv_speak, R.id.ll_loginout})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_search:
//                if (TextUtils.isEmpty(MyApplication.aCache.getAsString(AppConfig.APP_SERVER_TOKEN))) {
//                    Intent intent = new Intent(this, LoginActivity.class);
//                    startActivity(intent);
//                    return;
//                }

                if (isSpaking) {
                    //结束动画
                    // 释放资源
                    isSpaking = false;
                    stopAnimaiton();
                    mIat.stopListening();
                }
                requestPermission(Manifest.permission.RECORD_AUDIO);
                break;
            case R.id.iv_speak:
                if (!isSpaking) {
                    isSpaking = true;
                    //执行动画
                    //开始录音
                    startAnimation();
                    et_search.setText(null);
                    mIatResults.clear();
                    startSpeechListener();
                } else {
                    //结束动画
                    // 释放资源
                    isSpaking = false;
                    stopAnimaiton();
                    mIat.stopListening();
                }
                break;
            case R.id.ll_loginout:
                MyApplication.aCache.put(AppConfig.APP_SERVER_TOKEN, "");
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                this.finish();
                break;
        }
    }


    public void requestPermission(String... permission) {
        Acp.getmInstance(this).request(new AcpOptions.Builder().setPermissions(permission).build(), new AcpListener() {
            @Override
            public void onGranted() {
                //获取权限成功
                if (isHaveInternet) {

                    earchInfo(et_search.getText().toString());
                } else {
                    try {

                        dataBaseHelper = new DataBaseHelper(SearchActivity.this);
//                        dataBaseHelper.copyDBFile();
                        if (dataBaseHelper.checkDataBase()) {
                            dataBaseHelper.openDataBase();
                            Logger.log("数据库存在：");
                            searchSqlLite();
                        } else {
                            AppToast.showToast(SearchActivity.this, "请重启软件，并更新数据库", "");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onDenied(List<String> permissions) {
                //获取权限失败
                Logger.log("权限获取失败");
            }
        });
    }

    private void searchSqlLite() {
        showPersion(dataBaseHelper.searchPersion(et_search.getText().toString()));
    }

    private void searchCompany() {
        List<CompanyBean> beans = dataBaseHelper.searchCompany(et_search.getText().toString());
        if (beans == null || beans.size() == 0) {
            AppToast.showToast(this, "你要找的数据没有查到", "");
        } else {
            Intent intent = new Intent(SearchActivity.this, CompanyInfoActivity.class);
            intent.putExtra("companyBean", beans.get(0));
            startActivity(intent);
        }
    }

    /**
     * 参数设置
     *
     * @return
     */
    public void startSpeechListener() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        //此处用于设置dialog中不显示错误码信息
        //mIat.setParameter("view_tips_plain","false");

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, "3000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
//        mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "0");
        mIat.startListening(mRecognizerListener);
    }

    /**
     * 听写监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
//            showTip("开始说话");
        }

        @Override
        public void onError(SpeechError error) {
            Logger.log("发生错误：" + error.getPlainDescription(true) + "\n请确认是否已开通翻译功能");
            stopAnimaiton();
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
//            showTip("结束说话");
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            Log.d("TAg", results.getResultString());

            printResult(results);

        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            Log.d("TAG", "返回音频数据：" + data.length);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }

        et_search.setText(resultBuffer.toString());
        et_search.setSelection(et_search.length());
        if (isSpaking) {
            //结束动画
            // 释放资源
            isSpaking = false;
            stopAnimaiton();
            mIat.stopListening();
        }
    }

    /**
     * 开始动画
     */
    public void startAnimation() {
        animationDrawable.start();
    }

    /**
     * 结束动画
     */
    public void stopAnimaiton() {
        animationDrawable.selectDrawable(8);
        animationDrawable.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        animationDrawable = null;
        dataBaseHelper.close();
    }


    public void earchInfo(String search) {
        Api.searchInfo(searchHandler, MyApplication.aCache.getAsString(AppConfig.APP_SERVER_TOKEN), search);
    }

    /**
     * 能处理的返回0
     * 不能处理的返回-1
     *
     * @param searchText
     * @return
     */

    public int voiceSearchKey(String searchText) {
        Log.i("收索页面查询结果：", searchText);
        if (searchText.contains("返回桌面") || searchText.contains("返回系统")) {
            if (MyApplication.isFirstOpen) {
                MyApplication.isFirstOpen = false;
                return 0;
            }
            AppContext.closeActivityAll();
            return 0;
        }
        if (!TextUtils.isEmpty(searchText) && searchText.length() >= 2) {
            et_search.setText(searchText);
            et_search.setSelection(searchText.length());
            earchInfo(searchText);
        }
        return 0;
    }

    /**
     * 检查更新的回调
     *
     * @param version
     */
    @Override
    public void call(final Version version) {
        Acp.getmInstance(this).request(new AcpOptions.Builder().setPermissions(STORAGE_EXTERNAL).build(), new AcpListener() {
            @Override
            public void onGranted() {
                //获取权限成功
                DownloadService.startService(SearchActivity.this, "" + version.getDownload_path(), "升级本地数据库");
            }

            @Override
            public void onDenied(List<String> permissions) {
                //获取权限失败
            }
        });
    }

    /**
     * 访问SD卡
     */
    public static final String STORAGE_EXTERNAL[] = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
}
